package org.example.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Random;

@Aspect
@Component
public class OrderAspect {
    // 定义切点，匹配 OrderService 接口的 add、delete、find 方法
    @Pointcut("execution(* org.example.service.OrderService.*(..))")
    public void orderPointcut() {}

    // 前置增强
    @Before("orderPointcut()")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }

    // 后置增强
    @AfterReturning("execution(* org.example.service.OrderService.add(..)) || execution(* org.example.service.OrderService.delete(..))")
    public void afterReturningAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 获取方法返回值并输出
    @AfterReturning(pointcut = "orderPointcut()", returning = "result")
    public void afterReturningWithResultAdvice(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName + " 方法的返回值为：" + result);
    }

    // 输出方法执行时间
    @Around("orderPointcut()")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = pjp.proceed();
        long endTime = System.currentTimeMillis();
        String methodName = pjp.getSignature().getName();
        System.out.println(methodName + " 方法执行时间：" + (endTime - startTime) + " 毫秒");
        return result;
    }

    // 权限校验，针对 add 和 delete 方法
    @Around("execution(* org.example.service.OrderService.add(..)) || execution(* org.example.service.OrderService.delete(..))")
    public Object permissionCheckAdvice(ProceedingJoinPoint pjp) throws Throwable {
        Random random = new Random();
        int permission = random.nextInt(2); // 生成 0 或 1
        if (permission == 0) {
            System.out.println("有权限，执行方法");
            return pjp.proceed();
        } else {
            System.out.println("无权限，终止方法执行");
            return null;
        }
    }
}